
layui.use(['form', 'layer', 'laydate', 'table', 'upload'], function(){

    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        upload = layui.upload,
        table = layui.table;

    var datalist_url = $('.datalist_url').val();
    var add_url = $('.add_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var save_url = $('.save_url').val();
    var get_product_url = $('.get_product_url').val();
    var get_productlist_url = $('.get_productlist_url').val();
    var handle_url = $('.handle_url').val();


    //优惠券开始日期
    laydate.render({
        elem: '#start_time'
    });
    //优惠券结束日期
    laydate.render({
        elem: '#end_time'
    });


    // Table 列表
    var tableIns = table.render({
        elem: '#dataTable',
        url : datalist_url,
        page : true,
        cellMinWidth : 95,
        //height : "full-100",
        limit : 10,
        limits : [10, 20, 50, 100],
        id : "tableList",
        cols : [[
            /* {type: "checkbox", fixed:"left", width:50},*/
            {field: 'key', title: '序号', width:80, align:"center"},
            {field: 'name', title: '活动主题', minWidth:240},
            {field: 'f_name', title: '副标题', align:'center'},
            {field: 'mName', title: '推送对象', align:'center'},
            {field: 'start_time', title: '开始时间', align:'center', minWidth:110, sort: true},
            {field: 'end_time', title: '结束时间', align:'center', minWidth:110, sort: true},
            {field: 'create_date', title: '推送时间', align:'center', minWidth:110, sort: true},
            /*{title: '操作', minWidth:175, templet:'#handleBar', fixed:"right", align:"center"},*/
            {title: '操作', fixed:"right", align:"center", minWidth:140, templet:function(data){
                var html = '';
                //html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit" href="'+edit_url+'?id='+data.id+'"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
                html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
                /*html += '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>';*/

                return html;
            }}
        ]]
    });

    // 搜索
    $(".search_btn").on("click", function(){
        if ($('.title').val() != ''){
            var name = $('.searchBox').find('input[name=name]').val();
        }
        if ($('.coupon_purpose').val() != '') {
            var coupon_purpose = $('.coupon_purpose').val();
        }
        if ($('.coupon_type').val() != '') {
            var coupon_type = $('.coupon_type').val();
        }
        if ($('.time').val() != '') {
            var time = $('.time').val();
        }
        table.reload("tableList", {
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: {
                name: name,
                coupon_purpose: coupon_purpose,
                coupon_type: coupon_type,
                time: time,
            }
        });
    });

    // 批量删除
    $(".delAll_btn").on("click", function(){
        var checkStatus = table.checkStatus('tableList'),
            data = checkStatus.data,
            ids = [];
        if(data.length > 0) {
            for (var i in data) {
                ids.push(data[i].id);
            }
            layer.confirm('确定删除选中的数据？', {icon: 3, title: '提示信息'}, function (index) {
                $.ajax({
                    url: delete_url,
                    data: {"ids": ids},
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg('删除成功', {icon: 1});
                            tableIns.reload();
                            layer.close(index);
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function (data) {
                        layer.msg("服务器无响应");
                    }
                });
            })
        }else{
            layer.msg("请选择需要删除的数据");
        }
    });

    $('.add_btn').on('click', function(){
        formHtml();
    });


    // 列表操作
    table.on('tool(dataTable)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        // 删除
        if (layEvent === 'del') {
            layer.confirm('确定删除此数据？',{icon:3, title:'提示信息'},function(index){
                $.ajax({
                    url: delete_url,
                    data: {"id": data.id},
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg('已删除', {icon: 1, time: 1000});
                            tableIns.reload();
                            layer.close(index);
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function (data) {
                        layer.msg("服务器无响应");
                    }
                });
            });
        } else if(layEvent === 'edit'){
            formHtml(data);
        }
    });

    // Form 表单
    function formHtml(data){
        var content = add_url;

        if(data){
            content = edit_url + '?id=' + data.id;
        }
        // 右侧面板
        var index = layer.open({
            type: 2,
            anim: -1,
            title: false,
            closeBtn: false,
            offset: 'r',
            shade: 0.2,
            //, shadeClose: true // 是否点击遮罩关闭
            skin: 'layui-anim layui-anim-rl layui-layer-adminRight',
            area: '800px',
            top: 0,
            content: content
        });
    }
    //是否选择优惠券
    $(function(){
        $(".downpanel").on("click",".layui-select-title",function(e){
            var $select=$(this).parents(".layui-form-select");
            $(".layui-form-select").not($select).removeClass("layui-form-selected");
            $select.addClass("layui-form-selected");
            e.stopPropagation();
        }).on("click",".layui-form-checkbox",function(e){
            e.stopPropagation();
            var a = $("input[type='checkbox']:checked").length-2;
            $('.couponNumber').val('已选择 '+a+' 张优惠券');
        });
    });


    $('.addPro-btn').on('click', function(){
        top.layer.open({
            type: 2,
            anim: 1,
            title: '选择商品',
            shade: 0.2,
            skin: 'layui-anim layui-anim-rl layui-layer-Elasticframe',
            area: ['900px','700px'],
            content: get_product_url,
            yes:function () {
                sessionProduct.reload();
            }
        });
    });

    var sessionProduct = table.render({
        elem: '#dataTable01',
        url : get_productlist_url,
        page : false,
        cellMinWidth : 95,
        limit : 10,
        limits : [10, 20, 50, 100],
        id : "tableList",
        initSort: {
            field: 'create_date' // 排序字段，对应 cols 设定的各字段名
            ,type: 'desc' // 排序方式  asc: 升序、desc: 降序、null: 默认排序
        },
        cols : [[
            {field: "name", title:"商品名称",align:'center',minWidth:140},
            {field: 'bar_code', title: '条码',align:'center', minWidth:180},
            {field: 'typeName', title: '分类', align:'center', sort: true},
            {field: 'price', title: '销售价',align:'center', minWidth:80},
            {title: '操作', fixed:"right", align:"center", minWidth:140, templet:function(data){
                var html = '';
                //html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit" href="'+edit_url+'?id='+data.id+'"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
                html += '<button type="button" class="layui-btn " lay-event="purchase-add">选取 <input type="text" style="display:none" value="' +
                    ''+data.id+'" name="product_id"></button>'  ;
                return html;
            }}
        ]]
    });



    // 列表操作
    table.on('tool(dataTable01)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        //console.log(data);
        // 选取
        if (layEvent == 'purchase-add') {
            var index = parent.layer.getFrameIndex(window.name);
            layer.msg('选择成功', {icon: 1, time: 1000});
            var rule_length = index / 2;
            var $html = '';
            $html += '<div class="layui-form-item layui-form-text rule-group">';
            $html += '<div class="layui-inline">';
            $html += '<label class="layui-form-label">商品'+rule_length+'</label>';
            $html += '<div class="layui-input-inline">';
            $html += '<input type="hidden" class="layui-input " name="pro_id[]" value="'+data.id+'" maxlength="10" placeholder="元" autocomplete="off">';
            $html += '<div style="line-height: 39px; width: 300px">'+data.name+'</div>';
            $html += '</div>';
            $html += '</div>';
            $html += '<div class="layui-inline">';
            $html += '<div class="layui-input-inline">';
            $html += '<button type="button" class="layui-btn layui-btn-danger delRule-btn"><i class="layui-icon layui-icon-delete"></i></button>';
            $html += '</div>';
            $html += '</div>';

            parent.layer.getChildFrame('.payment-rule-group', 1).append($html);
            console.log(index);
            layer.close(index);
        }
    });


    // 删除商品
    $('.payment-rule-group').on('click', '.delRule-btn', function(){
        $(this).parents('.rule-group').remove();
    });

    //是否需要优惠券
    form.on('switch(is_coupon)', function(data){
        if(this.checked){
            $('#is_coupon').prop('checked',true);
            $('.is_coupon').removeClass('layui-hide')
        }else {
            $("#is_coupon").removeAttr('checked');
            $('.is_coupon').addClass('layui-hide');
        }
        form.render();
    });

    //是否插入商品
    form.on('switch(is_product)', function(data){
        if(this.checked){
            $('#is_product').prop('checked',true);
            $('.is_product_text').removeClass('layui-hide')
        }else {
            $("#is_product").removeAttr('checked');
            $('.is_product_text').addClass('layui-hide');
        }
        form.render();
    });


    // 表单提交
    form.on("submit(laySave)", function(data){
        //弹出loading
        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});

        $.ajax({
            url: save_url,
            data: data.field,
            type: "post",
            dataType: "json",
            success: function(res){
                top.layer.close(index);
                top.layer.msg(res.msg);
                if(res.code == 1){
                    // var index = parent.layer.getFrameIndex(window.name);
                    // // 关闭当前frame
                    // parent.layer.close(index);

                    layer.closeAll("iframe");
                    //parent.window.tableIns.reload();
                    parent.layui.table.reload('tableList', {});
                    // 刷新父页面
                    parent.location.reload();
                }
            },
            error:function(data){
                layer.msg("服务器无响应");
            }
        });
    })
});